#include "form1.h"
#include "ui_form1.h"
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QJsonValue>
#include <QJsonArray>
#include <QByteArray>
#include <QUrl>
#include <QFile>

//test git333

Form1::Form1(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Form1)
{
    ui->setupUi(this);
    //new一个网络管理对象
    m_ipManager = new QNetworkAccessManager(this);  //  net connection tool ,duty is to connect to the server
    //declare  connect relationship ,when receive the response ,call the slot function,response is finished signal
    connect(m_ipManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onGetIp(QNetworkReply*)));

    m_locManager=new QNetworkAccessManager(this);  //net connection tool ,duty is to connect to the server for location
    //declare  connect relationship ,when receive the response ,call the slot function,response is finished signal
    connect(m_locManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onGetCurrentLoc(QNetworkReply*)));

    m_mapManager=new QNetworkAccessManager(this);   //net connection tool ,duty is to connect to the server for map query map
    //！！！
    //connect(m_mapManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onSendMapRequest()));
    qDebug() << "Form1";

}

Form1::~Form1()
{
    delete ui;
}

void Form1::on_pushButton_clicked()
{
    //根据URL(http://t.weather.itboy.net/api/weather/city/101010100)http请求查询温度信息
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);   //
    QNetworkRequest request;   //请求
    request.setUrl(QUrl("http://t.weather.itboy.net/api/weather/city/101010100"));
    QNetworkReply *reply = manager->get(request);
    connect(reply, &QNetworkReply::finished, [=](){
        if(reply->error() == QNetworkReply::NoError)
        {
            QByteArray data = reply->readAll();
            QJsonParseError json_error;
            QJsonDocument doc = QJsonDocument::fromJson(data, &json_error);
            if(json_error.error == QJsonParseError::NoError)
            {
                if(doc.isObject())
                {
                    QJsonObject obj = doc.object();
                    if(obj.contains("data"))
                    {
                        QJsonValue value = obj.value("data");
                        if(value.isObject())
                        {
                            QJsonObject data = value.toObject();
                            if(data.contains("wendu"))
                            {
                                QJsonValue wendu = data.value("wendu");
                                ui->label->setText("温度：" + wendu.toString());
                            }
                        }
                    }
                }
            }
        }
        reply->deleteLater();    //释放资源
    });


}

void Form1::onGetIp(QNetworkReply *reply)
{
    //get the ip address,by ip value query the location
    QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll());
    QJsonObject jsonObj = jsonDoc.object();
    currentIp=jsonObj.value("origin").toString();
    qDebug() << "Current IP:" << currentIp;
    //by ip value query the location
    getLocation();

}


//json数据的一个样本如下
// {
//     "address": "CN|辽宁省|大连市|None|None|100|75",
//     "content": {
//         "address_detail": {
//             "province": "辽宁省",
//             "city": "大连市",
//             "district": "",
//             "street": "",
//             "street_number": "",
//             "city_code": 167,
//             "adcode": "210200"
//         },
//         "address": "辽宁省大连市",
//         "point": {
//             "x": "13539005.4",
//             "y": "4682974.61"
//         }
//     },
//     "status": 0
// }

void Form1::onGetCurrentLoc(QNetworkReply * reply)
{
    //根据经纬度发起查询地图
    QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll());


    //parse the json data,get the location data from the json data
    QJsonObject jsonObj = jsonDoc.object();
    QJsonObject contentObj = jsonObj.value("content").toObject();
    QJsonObject pointObj = contentObj.value("point").toObject();
    m_lng = pointObj.value("x").toString().toDouble();
    m_lat = pointObj.value("y").toString().toDouble();
    qDebug() << "经度:" << pointObj.value("x").toString() << "纬度:" << pointObj.value("y").toString();
    //根据经纬度发起查询地图请求
    //发起查询地图请求
    sendMapRequest();

}

void Form1::onSendMapRequest()
{
    qDebug() << "onSendMapRequest";

    //删除原有的地图图片 使用系统命令删除
    system("del map.png");
    //文件对象
    mapFile.setFileName(m_mapFileName);

    //读取文件流，保存文件到本地,
    //open 没有则新建文件，打开
    mapFile.open(QIODevice::WriteOnly| QIODevice::Truncate);    //Truncate  清空文件内容  if file already exists  it will be truncated,   if file does not exist, it will be created
    m_timer.start(2);  //定时器，2毫秒后执行，  2毫秒后执行，写入文件
    connect(&m_timer,&QTimer::timeout,[=](){
        m_timer.stop();
        mapFile.write(m_mapReply->readAll());
        mapFile.close();

        QPixmap pixmap;   //QPixmap  QPixmap类是用于处理图像的类。它是一个基于设备无关的图像表示，可以用于显示图像或者在设备上绘制图像。
        if(pixmap.load(m_mapFileName)){
            ui->mapWidget->setStyleSheet("QWidget{border-image:url(./map.png);}");
        }

    });
















}

void Form1::getIp()
{
  // by m_ipManager query ip
    QUrl url("http://httpbin.org/ip");  //declare the url
    QNetworkRequest request(url);  //declare the request
    m_ipManager->get(request);   //send the request
}

void Form1::getLocation()
{
    //by ip address ,query the location
    QUrl url("http://api.map.baidu.com/location/ip?ip="+currentIp+"&coor=bd09ll&ak="+ak);
    qDebug() << "query local url:" << url.url();
    QNetworkRequest request(url);
    m_locManager->get(request);
}

void Form1::sendMapRequest()
{

    qDebug() << "sendMapRequest--------------";
     //disconnect last http request and response
    if(m_mapReply!=NULL)
    {
        m_mapReply->disconnect();
        disconnect(m_mapManager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onSendMapRequest()));

    }
    //disconnect sigal and slot

    //by location query the map, use  m_mapManager
    QString url="http://api.map.baidu.com/staticimage/v2?ak="+ak+"&center="+QString::number(m_lng)+","+QString::number(m_lat)+"&width=1024&height=768&zoom="+QString::number(m_zoom);
    qDebug() << "url:" << url;
    QNetworkRequest request(url);
    m_mapReply=m_mapManager->get(request);

    //当m_mapReply 发出信号readyread时，我们调用对应的槽函数
    connect(m_mapReply,SIGNAL(readyRead()),this,SLOT(onSendMapRequest()));



}



void Form1::on_q_clicked()
{
    getIp();
}


void Form1::on_pushButton_2_clicked()
{





}

